<?php


namespace App\Services;


use App\Models\DriverCar;
use App\Repositories\CarRepository;
use Illuminate\Support\Facades\DB;

class CarService extends BaseService
{

    protected $repository;

    public function __construct()
    {
        $this->repository = new CarRepository();
    }


    /**
     * 保存车辆信息
     * @param array $data
     * @return bool
     * @Author 姿势就是力量
     */
    public function saveData(array $data)
    {
        DB::beginTransaction();
        try {
            $driver = [];
            if (isset($data['driver'])) {
                $driver = $data['driver'];
                $count = array_count_values(array_column($driver, 'host'));
                if (isset($count[1]) && $count[1] > 1) {
                    throw new \Exception('一辆车只能有一个主司机');
                }
                unset($data['driver']);
            }

            // 车牌号是否已注册
            if (isset($data['id']) && $data['id']) {
                (new DriverCar())->where('car_id', $data['id'])->delete();
            } else {
                $car = $this->repository->firstBy('number', $data['number'], ['number']);
                if ($car) throw new \Exception('该车牌号已被注册');
            }

            //车辆限行处理
            if ($data['restriction']) {
                $data['restriction'] = implode(',', $data['restriction']);
            }

            $car = $this->repository->saveData($data);
            if (!$car) throw new \Exception('车辆信息保存失败');
            // 司机车辆信息
            if ($driver) {
                $params = [];
                foreach ($driver as $key => $item) {
                    $params[] = [
                        'car_id' => (int)$car->id,
                        'driver_id' => (int)$item['id'],
                        'host' => (string)$item['host'],
                    ];
                }
                DriverCar::query()->insert($params);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();

            return $this->setError($e->getMessage());
        }

        return true;
    }

}
